<script>
import config from "./config";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { getVersion } from "@/api/login";
import { showConfirm } from "@/utils/common";

export default {
  onLaunch: function () {
    this.initApp();
  },
  methods: {
    // 初始化应用
    initApp() {
      // 初始化应用配置
      this.initConfig();
      // 检查用户登录状态
      this.checkLogin();
      this.getVersion();
    },
    initConfig() {
      this.globalData.config = config;
    },
    checkLogin() {
      if (!getToken()) {
        this.$tab.reLaunch("/pages/login/login");
      } else {
        this.$tab.reLaunch("/pages/home/index");
      }
    },
    getVersion() {
      const that = this;
      getVersion().then((res) => {
        if (res.result.versionNo !== config.appInfo.version) {
          showConfirm("软件有新版本，请更新").then((obj) => {
            if (obj.confirm) {
              uni.downloadFile({
                url: res.result.url,
                success: (downloadResult) => {
                  if (downloadResult.statusCode === 200) {
                    plus.runtime.install(
                      downloadResult.tempFilePath,
                      {
                        force: false,
                      },
                      function () {
                        console.log("install success...");
                        that.$modal.msgSuccess("更新成功");
                        setTimeout(() => {
                          plus.runtime.restart();
                        }, 1500);
                      },
                      function (e) {
                        console.error("install fail...");
                      }
                    );
                  }
                },
              });
            } else if (res.cancel) {
              plus.runtime.quit();
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="scss">
@import "@/static/scss/index.scss";
</style>
